﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tracy.CoreLib.Data;
using Tracy.CoreLib;
using Tracy.Engine;
using CoreLib.Message;
namespace Tracy
{
    public partial class FormFeedSource : AbstractMessageHandlerForm
    {
        private bool changed = false;
        /// <summary>
        /// 是否做过更改
        /// </summary>
        public bool Changed
        {
            get { return changed; }
        }

        private bool verified = false;
        private int verifyMode = 0; //0: ButtonOK; 1: ButtonVerify; 2:FormClosing
        
        private RssModel testRss = null;//临时的RssModel

        private TracyEngine tracyEngine = null;
        
        private DateTime lastVerified;
        
        RssFeedSource newSource = null;
        /// <summary>
        /// 新建的RssFeedSource
        /// </summary>
        public RssFeedSource NewSource
        {
            get { return newSource; }
        }

        #region 构造函数
        public FormFeedSource(TracyEngine engine) 
        {
            InitializeComponent();
            this.tracyEngine = engine;
            Initiation();
        }

        public FormFeedSource(RssFeedSource rss, TracyEngine engine)
        {
            InitializeComponent();
            newSource = rss;
            this.tracyEngine = engine;
            Initiation();
        }
        #endregion

        /// <summary>
        /// 加载SiteSchema
        /// </summary>
        private void Initiation()
        {
            foreach (SiteSchema ss in tracyEngine.GetSiteSchemas())
            {
                comboBoxSchema.Items.Add(ss);
            }
            if (comboBoxSchema.Items.Count > 0)
            {
                comboBoxSchema.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void FormFeedSource_Load(object sender, EventArgs e)
        {
            tracyEngine.OnMessageProcessed+=new EventHandler<global::CoreLib.Message.TracyMessageEventArgs>(tracyEngine_OnMessageProcessed);
            if (newSource != null)
            {
                textBoxTitle.Text = newSource.Title;
                textBoxLink.Text = newSource.Link;
                textBoxDescription.Text = newSource.Description;
                comboBoxSchema.SelectedItem = tracyEngine.GetSiteSchemas().GetItemById(newSource.SchemaId);
                buttonOK.Enabled = true;
                changed = false;//修改模式，默认未更改状态
            }
            else
            {
                changed = true;//新建模式
            }
            
        }

        /// <summary>
        /// 发送验证链接消息
        /// </summary>
        private void VerifyLink()
        {
            buttonVerify.Enabled = false;
            buttonOK.Enabled = false;
            textBoxLink.Enabled = false;
            tracyEngine.EnqueueMessage(new TestFeedMessage(this, textBoxLink.Text));
        }

        /// <summary>
        /// 验证链接
        /// </summary>
        private void buttonVerify_Click(object sender, EventArgs e)
        {
            verifyMode = 1;
            VerifyLink();
        }

        /// <summary>
        /// 验证并保存结果
        /// </summary>
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (changed)
            {
                //做了更改，需要重新验证
                verifyMode = 0;
                if (!verified)
                {
                    //尚未验证链接
                    VerifyLink();
                }
                else
                {
                    //已经验证过，直接保存结果
                    EndTestFeed();
                }
            }
            else
            {
                //未作更改，不保存
                this.Close();
            }

        }

        #region 是否更改过
        private void textBoxLink_TextChanged(object sender, EventArgs e)
        {
            changed = true;
            verified = false;
        }

        private void textBoxTitle_TextChanged(object sender, EventArgs e)
        {
            changed = true;
        }

        private void textBoxDescription_TextChanged(object sender, EventArgs e)
        {
            changed = true;
        }

        private void comboBoxType_TextChanged(object sender, EventArgs e)
        {
            changed = true;
        }

        private void comboBoxSchema_SelectedIndexChanged(object sender, EventArgs e)
        {
            changed = true;
        }
        private void FormFeedSource_FormClosing(object sender, FormClosingEventArgs e)
        {
            verifyMode = 2;
        }
        #endregion

        #region 消息处理
        /// <summary>
        /// 验证消息返回
        /// </summary>
        protected override void HandleMessageReceived(ITracyMessage msg)
        {
            if (msg is TestFeedMessage)
            {
                buttonVerify.Enabled = true;
                textBoxLink.Enabled = true;
            }
        }

        /// <summary>
        /// 验证异常处理
        /// </summary>
        protected override void HandleException(Exception e)
        {
            MessageBox.Show("RSS链接验证失败：\r\n" + e.Message);
            verified = false;
        }

        /// <summary>
        /// 处理消息
        /// </summary>
        protected override void EndProcessMessage(ITracyMessage msg)
        {
            if (msg.Sender == this)//由本窗体发出的消息
            {
                if (msg is TestFeedMessage)
                {
                    testRss = (RssModel)msg.Result;
                    lastVerified = DateTime.Now;
                    verified = true;
                    EndTestFeed();
                }
            }
        }

        /// <summary>
        /// 处理验证结果
        /// </summary>
        private void EndTestFeed()
        {
            if (verifyMode == 1)//验证按钮
            {
                if (testRss != null)
                {
                    //显示验证结果
                    textBoxTitle.Text = testRss.Channel.Title;
                    textBoxDescription.Text = testRss.Channel.Description;
                    buttonOK.Enabled = true;
                    string msg = CommonFunctions.CollectionToString((FilterEngine.ApplySchema(testRss, (SiteSchema)comboBoxSchema.SelectedItem)));
                    if (msg == "")
                    {
                        MessageBox.Show(Constants.CONST_MOE_MESSAGE_EMPTYRESULT);
                    }
                    else
                    {
                        MessageBox.Show(msg);
                    }
                }
                else
                {
                    buttonOK.Enabled = false;
                }
            }
            else if (verifyMode == 0)//确认按钮
            {
                if (testRss != null)
                {
                    //生成新的RssFeedSource
                    newSource = new RssFeedSource();
                    newSource.Title = textBoxTitle.Text;
                    newSource.Description = textBoxDescription.Text;
                    newSource.Link = textBoxLink.Text;
                    newSource.LastUpdate = lastVerified;
                    newSource.OriginalRss = testRss;
                    newSource.SchemaId = ((SiteSchema)comboBoxSchema.SelectedItem).Id;
                    this.DialogResult = DialogResult.OK;
                }
                else//取消
                {
                    return;
                }
            }
        }

        #endregion
    }
}
